package com.unm.core;

import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.io.Reader;
import java.io.BufferedReader;
import oracle.sql.CLOB;
import org.json.JSONException;  
import org.json.JSONObject;
import org.json.JSONArray;
import java.util.Map;
import java.util.Iterator;
import java.sql.*; 

public class Go extends HttpServlet {
	 
	String action_code = null;
	IHandler handler = null;
	PreparedStatement pstmt = null;  
	Connection conn = null;   
	private static final Hashtable htInitSql = new Hashtable();
	private static final Hashtable htSearchSql = new Hashtable();
	
	public Go() {}
	
	  public void doGet(HttpServletRequest request, HttpServletResponse response) throws
	      ServletException, IOException {		  
		  performTask(request, response);
	  }
	
	  public void doPost(HttpServletRequest request, HttpServletResponse response) throws
	      ServletException, IOException {
		  performTask(request, response);
	  }
	    public static String doValue(Connection conn, String sql)
		    throws Exception
		{
	    	PreparedStatement pstmt = conn.prepareStatement(sql);
	    	ResultSet dbr = pstmt.executeQuery();
		    String val = "";
		    if(dbr.next())
		    	val = dbr.getString(1);
		    dbr.close();
		    pstmt.close();
		    return val;
		}

	  private void gotoPath(String path, HttpServletRequest req, HttpServletResponse res) 
	  throws Exception {
		  getServletConfig().getServletContext().getRequestDispatcher( path).
		  forward(req, res);
	  }

	  public void performTask(HttpServletRequest req, HttpServletResponse res) throws
	      ServletException, IOException {
		try {
			System.out.println("<begin>");
			
			String dbUrl = Config.getDBUrl(0);
			Class.forName("oracle.jdbc.driver.OracleDriver");   
            conn = DriverManager.getConnection("jdbc:oracle:thin:"+dbUrl);   
             
	        //if(action_code.equals("login"))
	        //else if(action_code.equals("loginout"))
	        //else { 
	        // 检查session
	        // 检查权限
	        
	        			
			String er = "";
			String data = "";
			String layout = "";
			String exec = "";
	        String action=req.getParameter("do");
	        int mydo = Integer.parseInt(action);
	        conn.setAutoCommit(false);
	        if(action!=null)
	        {
	        	// 列表和显示和编辑需要main，保存和删除需要转向
	        	action = "select * from u_action1 where id = ?";
	        	pstmt = conn.prepareStatement(action);
	            pstmt.setInt(1,mydo );
		    	ResultSet dbr = pstmt.executeQuery();
	        	if(dbr.next())
	        	{
					String cfg = dbr.getString("cfg");
					JSONObject Jcfg = new JSONObject(cfg);
					int win = Jcfg.getInt("win");
					String type = Jcfg.getString("mtype");//one单笔数据，more多笔数据，tree树数据，save保存数据，del删除数据
					String title = Jcfg.getString("title");//
					String mtable = Jcfg.getString("mtable");//
					String mkey = Jcfg.getString("mkey");//
					String stype = Jcfg.getString("stype");//
					String stable = Jcfg.getString("stable");//
					String skey = Jcfg.getString("skey");//
					String sforkey = Jcfg.getString("sforkey");//
					String sforsrc = Jcfg.getString("sforsrc");//
					String sql = Jcfg.getString("msql");//
					String[] cols = Jcfg.getString("mcols").split(",");// 要填充json的列
					//可设定初始化键值,例如 [{init:true;dept:1;}]
					//客户端传来的要查询的列名称，需要变成 s_列名才能接收
					String qcols = Jcfg.getString("qcols");//查询字段
					String datato = Jcfg.getString("datato");//数据去向，ap应用级，sys系统级，mod模块级，fun功能级，page页面级，logic业务级，tmp临时级
					String init = Jcfg.getString("init");//
					String trans = Jcfg.getString("trans");// 传递的数据 传递搜索的键值，例如id:'/id',pid:'/xid'
					String[] prelogic = Jcfg.getString("mprelogic").split(",");//
					String[] aftlogic = Jcfg.getString("maftlogic").split(",");//
					String nextact = Jcfg.getString("nextact");//执行完后的action					
					exec = Jcfg.getString("exec");
					
					Jcfg.put("ind", dbr.getString("id"));
					req.setAttribute("__cfg", Jcfg);
					
//公用数据准备////////////////// 
					JSONObject JData = new JSONObject("{}"); // 预设的值填充 
					JSONArray JarData = new JSONArray();
					
					String initSql = "";
					String[] arInit=init.split(",");
					
					String gridids=req.getParameter("argridid");
					String[] argridid = null;			        			        	
		        	if(gridids!=null&&gridids.length()>1) argridid = gridids.split(",");
		        	
			        for(int i=0;i<arInit.length;i++)
			        {
			        	String tmp = arInit[i];
			        	if(tmp.equalsIgnoreCase("")) continue;
			        	if(tmp.indexOf("/")>0)// 页面间传递参数时改名传递
			        	{
			        		String[] array1=tmp.split("/"); 
			        		htInitSql.put(array1[1], "="+new String(req.getParameter(array1[0]).getBytes("ISO-8859-1"),"utf-8"));// 接收的名字变成后面的名字
			        		if(type.equalsIgnoreCase("gridsave")&&argridid!=null&&argridid.length>0)
							{								
						        for(int j=0;j<argridid.length;j++)
						        {
						        	if(argridid[j].length()<1) continue;
						        	JData.put(argridid[j]+"_"+array1[1],new String(req.getParameter(array1[0]).getBytes("ISO-8859-1"),"utf-8"));
						        }
							}
			        		else
			        			JData.put(array1[1], new String(req.getParameter(array1[0]).getBytes("ISO-8859-1"),"utf-8"));
			        	}
			        	else if(tmp.indexOf("=")>0)// 页面间传递参数用固定数据
			        	{
			        		String[] array2=tmp.split("="); 
			        		htInitSql.put(array2[0], "="+array2[1]);
			        		
			        		if(type.equalsIgnoreCase("gridsave")&&argridid!=null&&argridid.length>0)
							{								
						        for(int j=0;j<argridid.length;j++)
						        {
						        	if(argridid[j].length()<1) continue;
						        	JData.put(argridid[j]+"_"+array2[0],"0");
						        }
							}
			        		else
			        		JData.put(array2[0],array2[1]);
			        	}
			        	else if(tmp.indexOf("$")>0)// 参数用session传递  and field=session(para)
			        	{
			        		String[] array2=tmp.split("$"); 
			        		htInitSql.put(array2[0], "="+req.getSession().getAttribute(array2[1]).toString());
			        		if(type.equalsIgnoreCase("gridsave")&&argridid!=null&&argridid.length>0)
							{								
						        for(int j=0;j<argridid.length;j++)
						        {
						        	if(argridid[j].length()<1) continue;
						        	JData.put(argridid[j]+"_"+array2[0],req.getSession().getAttribute(array2[1]).toString());
						        }
							}
			        		else
			        		JData.put(array2[0],req.getSession().getAttribute(array2[1]).toString());
			        	}
			        	else if(tmp.indexOf("@")>0)// 指定字段的数据集的值 无用？？
			        	{
			        		String[] array2=tmp.split("@"); 
//			        		try{
//			        			initSql+=" and "+array2[0]+"="+dbr.getString(array2[1]);
//			        		}catch(Exception e){throw e;}
			        	}
			        	else if(tmp.indexOf("#")>0)// 直接原名传递
			        	{   
			        		String[] array2=tmp.split("#"); 
			        		htInitSql.put(array2[0], "="+new String(req.getParameter(array2[1]).getBytes("ISO-8859-1"),"utf-8"));
			        		if(type.equalsIgnoreCase("gridsave")&&argridid!=null&&argridid.length>0)
							{								
						        for(int j=0;j<argridid.length;j++)
						        {
						        	if(argridid[j].length()<1) continue;
						        	JData.put(argridid[j]+"_"+array2[0],new String(req.getParameter(array2[1]).getBytes("ISO-8859-1"),"utf-8"));
						        }
							}
			        		else
			        		JData.put(array2[0],new String(req.getParameter(array2[1]).getBytes("ISO-8859-1"),"utf-8"));
			        	}
			        }
			        // gridsave的prelogic处理数据准备
			        if(type.equalsIgnoreCase("gridsave")&&argridid!=null&&argridid.length>0)
					{
						JData.put("argridid",gridids);
				        for(int i=0;i<argridid.length;i++)
				        {
				        	if(argridid[i].length()<1) continue;
				        	for(String col : cols)					        		
				        	{
				        		if(req.getParameter(argridid[i]+"_"+col)!=null)
				        			JData.put(argridid[i]+"_"+col,req.getParameter(argridid[i]+"_"+col));
				        		// 加有乱码？？JData.put(argridid[i]+"_"+col,new String(req.getParameter(argridid[i]+"_"+col).getBytes("ISO-8859-1"),"utf-8"));
				        	}
				        }
					}System.out.println("<griddata>"+JData.toString());
//公用数据准备////////////////// 
			        
			        
					// 前端传回的搜索字串
					 String searchSql = "";
					 JSONObject JsearchData = new JSONObject(qcols); // 
					 for (Iterator iter = JsearchData.keys(); iter.hasNext();) { 
					        String key = (String)iter.next();
					        if(JsearchData.getString(key).equalsIgnoreCase("="))
					        	htSearchSql.put(key, "='"+new String(req.getParameter("s_"+key).getBytes("ISO-8859-1"),"utf-8")+"'");// 接收 s_字段的方式					        	 
					        if(JsearchData.getString(key).equalsIgnoreCase("like"))
					        	htSearchSql.put(key, " like '%"+new String(req.getParameter("s_"+key).getBytes("ISO-8859-1"),"utf-8")+"%'");// 接收 s_字段的方式					        	 		        
					 }
					 if(searchSql.length()>0) searchSql=initSql.substring(4);
					 
					 // 传递参数
					String[] StrArray=trans.split(",");trans="";
			        for(int i=0;i<StrArray.length;i++)
			        {
			        	String tmp = StrArray[i];
			        	if(tmp.equalsIgnoreCase("")) continue;
			        	
			        	if(tmp.indexOf("/")>0)// 页面间传递参数时改名传递
			        	{
			        		String[] array1=tmp.split("/"); 
			        		trans+="&"+array1[1]+"="+new String(req.getParameter(array1[0]).getBytes("ISO-8859-1"),"utf-8");// 接收的名字变成后面的名字
			        	}
			        	else if(tmp.indexOf("=")>0)// 页面间传递参数用固定数据
			        	{
			        		String[] array2=tmp.split("="); 
			        		trans+="&"+array2[0]+"="+array2[1];
			        	}
			        	else if(tmp.indexOf("$")>0)// 参数用session传递  and field=session(para)
			        	{
			        		String[] array2=tmp.split("$"); 
			        		trans+="&"+array2[0]+"="+req.getSession().getAttribute(array2[1]).toString();
			        	}
			        	else if(tmp.indexOf("@")>0)// 指定字段的数据集的值
			        	{
			        		String[] array2=tmp.split("@"); 
			        		try{
			        			trans+="&"+array2[0]+"="+dbr.getString(array2[1]);
			        		}catch(Exception e){throw e;}
			        	}
			        	else // 直接原名传递
			        		trans+="&"+tmp+"="+new String(req.getParameter(tmp).getBytes("ISO-8859-1"),"utf-8");
			        }
			        
					 
			        
////////////////////// 处理前的业务逻辑 com.base.login:loginout,com.base.login:log
			        req.setAttribute("__data", JData);// JSONobject的数据格式
			        req.setAttribute("__ardata", JarData);// JSONArray的数据格式
					for(String locics : prelogic)
					{
						if(locics.length()<1) continue;
						req.setAttribute("__logic", locics);
				    	handler = HandlerManager.getHandler(conn,req);
			  	        if (handler == null) {throw new Exception("没有保存前业务逻辑!");}
			  	        try {  handler.doAction(conn,req);  }
			  	        catch (Exception e) { conn.rollback(); throw e; }
					}
					JData = (JSONObject)req.getAttribute("__data");
					JarData = (JSONArray)req.getAttribute("__ardata");
////////////////////// 处理前的业务逻辑 com.base.login:loginout,com.base.login:log
					
					if(type.equalsIgnoreCase("tblview"))
					{
						String id=req.getParameter(mkey);
						if(mtable.length()>0)
							sql = "select "+Jcfg.getString("mcols")+ " from "+mtable+" where "+mkey+"= ? ";
						if(initSql.length()>0||searchSql.length()>0) sql+=initSql+searchSql;
						if(id!=null&&id.length()>0) // 有数据的载入
						{
							JData.put(mkey,id);
							pstmt = conn.prepareStatement(sql);
				            pstmt.setInt(1,Integer.parseInt(id) );
					    	ResultSet dbr1 = pstmt.executeQuery();
					        if(dbr1.next())
					        	for(String col : cols) 	JData.put(col,dbr1.getString(col));
						}
					}
					if(type.equalsIgnoreCase("tbledit"))
					{
						String id=req.getParameter(mkey);
						if(mtable.length()>0)
							sql = "select "+Jcfg.getString("mcols")+ " from "+mtable+" where "+mkey+"="+id;
						if(initSql.length()>0||searchSql.length()>0) sql+=initSql+searchSql;
						if(id!=null&&id.length()>0) // 有数据的载入
						{
							JData.put(mkey,id);
							pstmt = conn.prepareStatement(sql);
				            pstmt.setInt(1,Integer.parseInt(id) );
					    	ResultSet dbr1 = pstmt.executeQuery();
					        if(dbr1.next())
					        	for(String col : cols) 	JData.put(col,dbr1.getString(col));
					        //System.out.println("<JData>"+JData);
						}
					}
					
					if(type.equalsIgnoreCase("gridview"))
					{
						if(mtable.length()>0)
							sql = "select "+mkey+","+Jcfg.getString("mcols")+ " from "+mtable;
						if(initSql.length()>0||searchSql.length()>0) sql+=" where "+initSql+searchSql;
						pstmt = conn.prepareStatement(sql);
				    	ResultSet dbr1 = pstmt.executeQuery();				
				        while(dbr1.next())
				        {
				        	String tline = "";
				        	JSONObject JartData = new JSONObject(JData);// 每行初始化公用数据
				        	for(String col : cols) 
				        	{
				        		Object tmp = dbr1.getString(col);
				        		JartData.put(col, (tmp==null?"":tmp));
				        	}		
				        	JartData.put(mkey, dbr1.getString(mkey));
				        	JarData.put(JartData);
				        }
					}					
					if(type.equalsIgnoreCase("gridedit"))
					{
						// gridview可以编辑
					}
					if(type.equalsIgnoreCase("tblgridview"))
					{
						
					}
					if(type.equalsIgnoreCase("tblgridedit"))
					{}
					if(type.equalsIgnoreCase("tblsave"))
					{
						String id=req.getParameter(mkey);
						if(id==null||id.length()<1)
						{
							if(sql.length()>0)
							{
								// 添加传入参数
								pstmt = conn.prepareStatement(sql);
						    	pstmt.executeQuery();
							}
							else if(mtable.length()>0)
							{
								String tmp = "";
								for(String col : cols) tmp+=",'"+JData.getString(col)+"'";
								String seq = "S_"+mtable.substring(2)+".NEXTVAL";
								sql = "insert into "+mtable+" ("+mkey+","+Jcfg.getString("mcols")+") values ("+seq+","+tmp.substring(1)+")";
								pstmt = conn.prepareStatement(sql);
						    	pstmt.executeQuery();
							}else
							{
								// 如果mtable和sql都没有，则不执行sql操作
							}
						}
						else
						{
							if(sql.length()>0)
							{
								pstmt = conn.prepareStatement(sql+" where "+mkey+"=?");
					            pstmt.setInt(1,Integer.parseInt(id) );
						    	ResultSet dbr1 = pstmt.executeQuery();
							}
							else if(mtable.length()>0)
							{
								String tmp = "";
								for(String col : cols)
									tmp+=","+col+"='"+JData.getString(col)+"'";
								sql = "update "+mtable+" set "+tmp.substring(1)+" where "+mkey+"="+id;
								System.out.println("<bef sql>"+sql);
								pstmt = conn.prepareStatement(sql);
					            pstmt.setInt(1,Integer.parseInt(id) );
						    	pstmt.executeQuery();
							}else
							{
								// 如果mtable和sql都没有，则不执行sql操作
							}
						}
					}
					if(type.equalsIgnoreCase("gridsave"))
					{
						String ids=req.getParameter("argridid");
						String tpsql = "begin";
						String tisql = "";
						if(ids!=null&&ids.length()>1)
						{
							String[] arid=ids.split(",");
					        for(int i=0;i<arid.length;i++)
					        {
					        	if(arid[i].length()<1) continue;
					        	if(arid[i].length()>3&&arid[i].substring(0,4).equalsIgnoreCase("comp"))
								{
									String tmp = "";
									for(String col : cols) tmp+=",'"+JData.getString(arid[i]+"_"+col)+"'";
									String seq = "S_"+mtable.substring(2)+".NEXTVAL";
									tisql=" insert into "+mtable+" ("+mkey+","+Jcfg.getString("mcols")+") values ("+seq+","+tmp.substring(1)+")";
									pstmt = conn.prepareStatement(tisql);
							    	pstmt.executeQuery();
									tisql="select S_"+mtable.substring(2)+".currval from dual";
									data+=",{"+arid[i]+":'"+doValue(conn, tisql)+"'}";
								}else
								{
									String tmp = "";
									for(String col : cols)
										tmp+=","+col+"='"+JData.getString(arid[i]+"_"+col)+"'";									
									tpsql+= " update "+mtable+" set "+tmp.substring(1)+" where "+mkey+"="+arid[i]+";";									
								}					        	
					        }
					        tpsql+=" end;";
 
//declare rtndata nvarchar2(2000);mKeyID NUMBER;
//begin  
//insert into t_vehicle_kind (id,code,name,org_id) values (S_vehicle_kind.NEXTVAL,'dd@g.com','singletab','0');
//select S_vehicle_kind.currval into mKeyID from dual;
//rtndata:=rtndata||',{comp_119:'||mKeyID||'}';
//insert into t_vehicle_kind (id,code,name,org_id) values (S_vehicle_kind.NEXTVAL,'dd@g.com','singletab','0');
//select S_vehicle_kind.currval into mKeyID from dual;
//rtndata:=rtndata||',{comp_121:'||mKeyID||'}';
//insert into t_vehicle_kind (id,code,name,org_id) values (S_vehicle_kind.NEXTVAL,'dd@g.com','singletab','0');
//select S_vehicle_kind.currval into mKeyID from dual;
//rtndata:=rtndata||',{comp_122:'||mKeyID||'}';
//dbms_output.put_line(rtndata); 
//end;
						}
						if(tpsql.length()>10) // 有update语句
						{
							pstmt = conn.prepareStatement(tpsql);
					    	pstmt.executeQuery();
						}
						System.out.println("<procsql>"+data);
						 if(data.length()>0) data="["+data.substring(1)+"]";
					     else data="[]";
					}
					
					if(type.equalsIgnoreCase("tblgridsave"))
					{
						String[] arStype=stype.split(",");
						String[] arStable=stable.split(",");
						String[] arSkey=skey.split(",");
						String[] scols = Jcfg.getString("scols").split(";");// 要填充json的列
						
						String id=req.getParameter(mkey);
						if(id==null||id.length()<1)// 新增操作
						{
							// table操作
							String tmp = "";
							for(String col : cols) tmp+=",'"+JData.getString(col)+"'";
							String seq = "S_"+mtable.substring(2)+".NEXTVAL";
							sql = "insert into "+mtable+" ("+mkey+","+Jcfg.getString("mcols")+") values ("+seq+","+tmp.substring(1)+")";
							pstmt = conn.prepareStatement(sql);
					    	pstmt.executeQuery();
							
							// 字表新增操作
							
							for(int t=0;t<arStype.length;t++)
				  	        {
								if(arStype[t].equalsIgnoreCase("tbl")) // table类型展示
				  	        	{			
									tmp = "";
									for(String col : scols[t].split(",")) tmp+=",'"+JData.getString(col)+"'";// 取得每个的值
									seq = "S_"+arStable[t].substring(2)+".NEXTVAL";
									sql = "insert into "+arStable[t]+" ("+arSkey[t]+","+scols[t]+") values ("+seq+","+tmp.substring(1)+")";
									pstmt = conn.prepareStatement(sql);
							    	pstmt.executeQuery();
				  	        	}
								if(arStype[t].equalsIgnoreCase("grid")) // gird数据展示
				  	        	{
									String ids=req.getParameter("argrid"+arSkey[t]);
									String tpsql = "begin";
									String tisql = "";
									if(ids!=null&&ids.length()>1)
									{
										String[] arid=ids.split(",");
								        for(int i=0;i<arid.length;i++)
								        {
								        	if(arid[i].length()<1) continue;
								        	if(arid[i].length()>3&&arid[i].substring(0,4).equalsIgnoreCase("comp"))
											{
												tmp = "";
												for(String col : scols[t].split(",")) tmp+=",'"+JData.getString(arid[i]+"_"+col)+"'";
												seq = "S_"+arStable[t].substring(2)+".NEXTVAL";
												tisql=" insert into "+arStable[t]+" ("+arSkey[t]+","+scols[t]+") values ("+seq+","+tmp.substring(1)+")";
												pstmt = conn.prepareStatement(sql);
										    	pstmt.executeQuery();
												tisql="select S_"+arStable[t].substring(2)+".currval from dual";
												data+=",{"+arid[i]+":'"+doValue(conn, tisql)+"'}";
											}else
											{
												tmp = "";
												for(String col : cols)
													tmp+=","+col+"='"+JData.getString(arid[i]+"_"+col)+"'";									
												tpsql+= " update "+mtable+" set "+tmp.substring(1)+" where "+mkey+"="+arid[i]+";";									
											}					        	
								        }
								        tpsql+=" end;";
								        pstmt = conn.prepareStatement(tpsql);
								    	pstmt.executeQuery();
									}
				  	        	}
				  	        }
						}
						else // 修改操作
						{
							// 主表修改保存
							String tmp = "";
							for(String col : cols)
								tmp+=","+col+"='"+JData.getString(col)+"'";
							sql = "update "+mtable+" set "+tmp.substring(1)+" where "+mkey+"=?";
							pstmt = conn.prepareStatement(sql);
				            pstmt.setInt(1,Integer.parseInt(id) );
					    	pstmt.executeQuery();
							
							for(int t=0;t<arStype.length;t++)
				  	        {
								if(arStype[t].equalsIgnoreCase("tbl")) // table类型展示
				  	        	{
									tmp = "";
									for(String col : cols)	tmp+=","+col+"='"+JData.getString(col)+"'";
									sql = "update "+mtable+" set "+tmp.substring(1)+" where "+mkey+"="+id;
									pstmt = conn.prepareStatement(sql);
						            pstmt.setInt(1,Integer.parseInt(id) );
							    	pstmt.executeQuery();
				  	        	}
								if(arStype[t].equalsIgnoreCase("grid")) // gird数据展示
				  	        	{
									String ids=req.getParameter("argrid"+arSkey[t]);
									String tpsql = "begin";
									String tisql = "";
									if(ids!=null&&ids.length()>1)
									{
										String[] arid=ids.split(",");
								        for(int i=0;i<arid.length;i++)
								        {
								        	if(arid[i].length()<1) continue;
								        	if(arid[i].length()>3&&arid[i].substring(0,4).equalsIgnoreCase("comp"))
											{
												tmp = "";
												for(String col : scols[t].split(",")) tmp+=",'"+JData.getString(arid[i]+"_"+col)+"'";
												String seq = "S_"+arStable[t].substring(2)+".NEXTVAL";
												tisql=" insert into "+arStable[t]+" ("+arSkey[t]+","+scols[t]+") values ("+seq+","+tmp.substring(1)+")";
												pstmt = conn.prepareStatement(tisql);
										    	pstmt.executeQuery();
												tisql="select S_"+arStable[t].substring(2)+".currval from dual";
												data+=",{"+arid[i]+":'"+doValue(conn, tisql)+"'}";
											}else
											{
												tmp = "";
												for(String col : cols)
													tmp+=","+col+"='"+JData.getString(arid[i]+"_"+col)+"'";									
												tpsql+= " update "+mtable+" set "+tmp.substring(1)+" where "+mkey+"="+arid[i]+";";									
											}					        	
								        }
								        tpsql+=" end;";
								        pstmt = conn.prepareStatement(tpsql);
								    	pstmt.executeQuery();
									}
				  	        	}
								 
				  	        }
						}
					}
					if(type.equalsIgnoreCase("tree"))
					{
							// 以后更改为依据数据库权限显示菜单
							String id=req.getParameter("id");
							if(id.equalsIgnoreCase("0"))
								layout="{title: '事务追踪',nodes: true,disabled: true},{title: '公告'},{title: '消息',nodes: true}";
							if(id.equalsIgnoreCase("1"))
								layout="{id:'7',title: '基本信息'},{id:'8',title: '外派车辆'},{id:'list_vehiclein',title: '内部用车'}";
					        if(id.equalsIgnoreCase("zy"))
					        	layout="{id:'600',title: '组织机构'},{id:'601',title: '新增计划(主子表)'},{id:'602',title: '单独tab',nodes: false},{id:'y1',title: '用户管理',nodes: false},{id:'y2',title: '用户管理',nodes: false}";
					        if(id.equalsIgnoreCase("hr"))
					        	layout="{title: '组织机构',nodes: true,array:[{id:'51',title: '机构定义',nodes: true},{id:'52',title: '人员编制',nodes: true},{id:'521',title: '角色定义',nodes: true},{id:'522',title: '角色人员',nodes: true}]},{title: '人员管理'},{id:'53',title: '能力管理',nodes: false},{id:'541',title: '培训管理',nodes: false},{id:'55',title: '绩效管理',nodes: true},{id:'56',title: '招聘管理',nodes: true},{id:'57',title: '薪资管理',nodes: true}";
					        if(id.equalsIgnoreCase("unfm"))
					        	layout="{id:'1',title: '系统及版本(grid编辑)'},{id:'2',title: '模块及功能'},{id:'4',title: '页面及逻辑',nodes: false},{id:'5',title: '配置列表',nodes: false},{id:'xx',title: '配置界面2',nodes: false}";
					         
					}else
					{
						CLOB clob =  (oracle.sql.CLOB)dbr.getClob("main");
			      		  if(clob!=null)
			      		  {
				      		  Reader is = clob.getCharacterStream();// 得到流
				      		  BufferedReader br = new BufferedReader(is);
				      		  String s = br.readLine();
				      		  StringBuffer sb = new StringBuffer();
				      		  while (s != null) {//执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
					      		 sb.append(s);
					      		 s = br.readLine();
				      		  }
				      		layout = sb.toString();	
			      		  }
					}
					
					
					
					// 确定数据的去向
					if(datato.equalsIgnoreCase("ap"))// 应用层级
					{
						
					}
					if(datato.equalsIgnoreCase("sys"))// 系统层级
					{
						
					}
					if(datato.equalsIgnoreCase("mod"))// 模块层级
					{
						
					}
					if(datato.equalsIgnoreCase("fun"))// 功能层级
					{
						
					}
					if(datato.equalsIgnoreCase("page"))// 页面层级
					{
						
					}
					if(datato.equalsIgnoreCase("logic"))// 逻辑层级
					{
						
					}
					if(datato.equalsIgnoreCase("tmp"))// 临时层级
					{
						
					}
					
		  	        ///////////// 保存操作////////////
		  	        
		  	        
		  	        ///////////// 保存操作////////////
////////////////////// 处理后的业务逻辑
					req.setAttribute("__data", JData);// JSONobject的数据格式
					req.setAttribute("__ardata", JarData);// JSONArray的数据格式
					for(String locics : aftlogic)
					{
						if(locics.length()<1) continue;
						req.setAttribute("__logic", locics);
			  	        handler = HandlerManager.getHandler(conn,req);
			  	        if (handler == null) {throw new Exception("没有保存后业务逻辑!");}
			  	        try {  handler.doAction(conn,req);  }
			  	        catch (Exception e) { conn.rollback(); throw e; }
					}
					JData = (JSONObject)req.getAttribute("__data");
					JarData = (JSONArray)req.getAttribute("__ardata");
//////////////////////处理后的业务逻辑
					
//生成返回数据/////////////////////////////////
					if(type.equalsIgnoreCase("gridview"))
					{
						 for (int i = 0; i < JarData.length(); i++) {
					            JSONObject jo = (JSONObject) JarData.get(i);
					            String tline = "";
					        	for(String col : cols) tline+=",{title:'"+jo.getString(col)+"'}";
					        	tline=tline.substring(1);					        	
					        	data += ",{id:'"+jo.getString(mkey)+"',array:["+tline+"]}";
					     }
					     if(data.length()>0) data="["+data.substring(1)+"]";
					     else data="[]";
					}
					if(type.equalsIgnoreCase("tblview"))
					{
						data="["+JData.toString()+"]";
					}
					if(type.equalsIgnoreCase("tbledit"))
					{
						//System.out.println("<datatbledit>"+JData.getString("cfgcode"));
						data="["+JData.toString()+"]";
					}     
	
					
	        	  
	      		  if(layout.length()>0)
	      		  {
		      		  if(win==1)
		      			layout="[{ctype:'win',title:'"+title+"',layout:'row',lyInf:{h:'lead'},lyCfg:{items:[{ css:'m:0,2px', template:'<span></span>',ctype:'base', clickDisabled:true},"+layout+"]}}]";
		      		  else
		      			  layout="["+layout+"]";
	      		  }else layout = "''";
	      		  // 传递需要传递的参数
	      		  if(trans.length()>0) exec+="gpara=\""+trans+"\";";
	      		  
	      		String if_d=req.getParameter("if_d");
	      		String if_e=req.getParameter("if_e");
	      		if(if_d!=null&&if_d.equals("-1")) data = "";
	      		if(if_e!=null&&if_e.equals("-1")) exec = "";
	      		  
	      		  String tt = "{_s_msgid:0,_s_msg:'',_s_lay:"+layout+",_s_data:"+(data.length()<1?"''":data)+",_s_exe:'"+exec+"'}";
			      req.setAttribute("data",tt);
//生成返回数据/////////////////////////////////	      		
	        	}else
	      		  {er="没有定义操作";} 
	        	
	        	

	        }else
	        {er = "参数错误，请咨询系统管理人员"; }
	        
	        String a=req.getParameter("do");
	        if(a!=null)
	        {
	        	if(a.equalsIgnoreCase("savelayout"))
	        	{
	        		req.setCharacterEncoding("utf-8");
	        		String ss=req.getParameter("cfgcode");
	        		
	        		//ss=java.net.URLDecoder.decode(ss, "UTF-8");
	        		ss=new String(ss.getBytes("8859_1"),"utf-8");
	        		ss=ss.replaceAll(" ","&nbsp;");
	        		ss=ss.replaceAll("\r\n","<br/>");
	        		ss=ss.replaceAll("\n\r","<br/>");
	        		ss=ss.replaceAll("\n","<br/>");
	        		ss=ss.replaceAll("\r","<br/>");
	        		ss=ss.replaceAll("[?]","");
	        		System.out.println("<code>"+ss);
	        		
//	        		
//	        		String sql = "insert into u_action1(id,main) values(5,empty_clob())"; 
//	        		DBPreparedStatement pstmt = con.prepareStatement(sql); 
//	        		pstmt.executeUpdate(); 
//	        		pstmt = null;
//	        		sql = "select main from u_action1 where id = 5 for update"; 
//	        		pstmt = con.prepareStatement(sql);
//	        		ResultSet rs = pstmt.executeQuery(); 
//	        		oracle.sql.CLOB clobtt = null; 
//	        		if(rs.next()){ 
//	        			clobtt = (oracle.sql.CLOB)rs.getClob(1); 
//	        		}
//	        		java.io.Writer wr = clobtt.getCharacterOutputStream();
//	        		wr.write(ss); 
//	        		wr.flush(); 
//	        		wr.close(); 
//	        		rs.close(); 
	        		
	        	}
	        }
	         	        
	        conn.commit();
	        System.out.println("<data>"+req.getAttribute("data"));
	        String next_url = Config.getWebPath()+"/data.go";
	        //System.out.println("<next_url>"+next_url);
	        gotoPath(next_url, req, res);
	         
	      }catch (Exception e) {
	    	  e.printStackTrace();
	      }
	      finally {
	        try {
	          if (conn != null && !conn.isClosed()) {
	            conn.close();
	          }
	        }
	        catch (Exception e) {
	        	System.out.println(e);
	        }
	      }
	}
}
